/**
 * @deprecated MutationObserver
 */

/**
 * 取消监听
 * @param {Node} el - Node节点
 * @param {MutationCallback} fn - MutationObserver的回调函数
 */
export function disconnect(el, fn) {
    if (el.observer && el.observer.has(fn)) {
        const { observer } = el.observer.get(fn)
            // const records = observer.takeRecords()
            // if (records.length) {
            //     fn(records)
            // }
        observer.disconnect()
        el.observer.delete(fn)
    }
}

/**
 * 绑定监听
 * @param {Node} el - Node节点
 * @param {MutationCallback} fn - MutationObserver的回调函数
 * @param {MutationObserverInit} option MutationObserver的配置项
 * @returns {MutationObserver}
 */
export function observe(el, fn, option) {
    if (!el.observer) {
        el.observer = new Map()
    } else {
        disconnect(el, fn)
    }
    const observer = new MutationObserver(fn)
    observer.observe(el, option)
    el.observer.set(fn, { observer, option })
    return observer
}

/**
 * 监听 attribute 变化
 * @param {Node} el - Node节点
 * @param {MutationCallback} fn - MutationObserver的回调函数
 * @param {Boolean} subtree 是否监听后代节点的 attribute 变化
 * @param {Array} attrs 监听指定的 attribute
 * @returns {MutationObserver}
 */
export function attribute(el, fn, subtree, attrs) {
    const option = {
        subtree: !!subtree,
        attributes: true,
        attributeOldValue: true,
    }
    if (Array.isArray(attrs)) {
        option.attributeFilter = attrs
    }
    return observe(el, fn, option)
}

/**
 * 监听子节点的增减
 * @param {Node} el Node节点
 * @param {MutationCallback} fn MutationObserver的回调函数
 * @param {Boolean} subtree 是否监听后代节点的 attribute 变化
 * @returns {MutationObserver}
 */
export function childList(el, fn, subtree) {
    return observe(el, fn, {
        childList: true,
        subtree: !!subtree,
    })
}

/**
 * 监听文本变化
 * @param {Node} el Node节点
 * @param {MutationCallback} fn MutationObserver的回调函数
 * @returns {MutationObserver}
 */
export function character(el, fn) {
    return observe(el, fn, {
        subtree: true,
        characterData: true,
        characterDataOldValue: true,
    })
}

export function resize(el, fn) {}